﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nancy.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SHRIS.MIS.Common.Util.Model;
using SHRIS.MIS.Entity.ScadaData;
using SHRIS.MIS.IService.APIExternal;
using SHRIS.MIS.Model.Param.APIExternal;
using SHRIS.MIS.Service.APIExternal;
using SHRIS.MIS.Web.Controllers;
using SHRIS.MIS.Web.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SHRIS.MIS.Web.Areas.OrderManage.Controllers
{
    [Area("OrderManage")]
    public class OrderPreviewController : BaseController
    {
        #region 服务注入
        private readonly IMapper _mapper;
        IOrderService _orderService;
        public OrderPreviewController(IMapper mapper, IOrderService orderService)
        {
            _mapper = mapper;
            _orderService = orderService;
        }
        #endregion

        #region 视图功能
        [AuthorizeFilter("order:preview")]
        public IActionResult OrderIndex()
        {
            return View();
        }

        [AuthorizeFilter("order:preview")]
        public IActionResult OrderSelect()
        {
            return View();
        }

        [AuthorizeFilter("order:preview")]
        public IActionResult OrderCreate()
        {
            return View();
        }

        [AuthorizeFilter("order:preview")]
        public IActionResult OrderDetails()
        {
            return View();
        }

        [AuthorizeFilter("order:preview")]
        public IActionResult ProductionDetails()
        {
            return View();
        }

        #endregion

        #region API服务
        /// <summary>
        /// 根据页码和数量获取没有完成的订单
        /// </summary>
        /// <param name="pageSize">页码</param>
        /// <param name="limit">数量</param>
        /// <returns>订单列表、订单总数值</returns>
        [HttpGet]
        public async Task<IActionResult> GetOrderNotFinished(int pageSize = 1, int limit = 10)
        {
            Pagination p = new Pagination();
            p.Sort = "UpdateTime";
            p.PageIndex = pageSize;
            p.PageSize = limit;
            var entityes = await _orderService.SearchOrdersNotFinished(p);
            var obj = new
            {
                data = entityes,
                total = p.TotalCount
            };
            return Json(obj);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="data">to_status为需要修改的状态,order为该订单基本信息</param>
        /// <returns>ResponseDto</returns>
        [HttpPost]
        public async Task<IActionResult> ModifOrderStatus([FromBody] object data)
        {
            ResponseDto resultEntity = new ResponseDto();
            resultEntity.SerialID = Guid.NewGuid().ToString();
            resultEntity.Status = "fail";
            try
            {
                var getData = ChangeJsonObject(data);
                int to_status = int.Parse((getData["to_status"]).ToString());
                var orderInfo = getData["order"];
                var order = ChangeJsonObject(orderInfo);
                string orderCode = order["OrderCode"].ToString();
                if (to_status == 1)
                {
                    // 查看有没有在开始的订单
                    var isStartOrder = await _orderService.SearchOrdersIsStart();
                    if (isStartOrder.Count<OrderEntity>() == 0)
                    {
                        int result = await _orderService.ModifOrderStatus(orderCode, to_status);
                        resultEntity.Status = "success";
                    }
                    else
                    {
                        string startDeviceCode = null;
                        foreach (OrderEntity startOrder in isStartOrder)
                        {
                            startDeviceCode = startOrder.OrderCode;
                        }
                        resultEntity.Message = "已存在开始的订单，订单编号："+ startDeviceCode;
                    }
                }
                else
                {
                    int result = await _orderService.ModifOrderStatus(orderCode, to_status);
                    resultEntity.Status = "success";
                }
                
            }
            catch(Exception ex)
            {
                resultEntity.Message = ex.Message;
            }                       
            return Json(resultEntity);
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="pageSize">页码</param>
        /// <param name="limit">数量</param>
        /// <param name="stime">起始时间</param>
        /// <param name="etime">终止时间</param>
        /// <param name="OrderCode">订单编码</param>
        /// <param name="MaterialId">物料编码</param>
        /// <param name="MaterialName">物料名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> SelectOrderByParams(int pageSize, int limit,DateTimeOffset stime, DateTimeOffset etime,string OrderCode, string MaterialId,string MaterialName)
        {
            Pagination p = new Pagination();
            p.Sort = "UpdateTime";
            p.PageIndex = pageSize;
            p.PageSize = limit;
            var entityes = await _orderService.SearchOrderByParams(stime, etime, OrderCode, MaterialId, MaterialName, p);
            var obj = new
            {
                data = entityes,
                total = p.TotalCount
            };
            return Json(obj);
        }

        /// <summary>
        /// 获取订单的生命周期
        /// </summary>
        /// <param name="orderCode">订单编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetOrderLifecycle(string orderCode)
        {
            var entityes = await _orderService.SearchOrderLifecycle(orderCode);
            var obj = new
            {
                data = entityes
            };
            return Json(obj);
        }

        /// <summary>
        /// 获取订单所有工件的基本生命周期
        /// </summary>
        /// <param name="orderCode">订单编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetOrderProductionDetails(string orderCode)
        {
            // 1、查找订单基本信息
            var orderInfo = await _orderService.SearchOrderByOrderCode(orderCode);

            // 2、查找订单工件的完成情况
            var orderProgress = await _orderService.SearchOrderProgress(orderCode);

            //3、查找所有工件的基本生命周期
            Pagination p = new Pagination();
            p.Sort = "UpdateTime";
            p.PageIndex = 1;
            p.PageSize = 1000;
            var productionLife = await _orderService.SearchProductionByOrderCode(orderCode,p);

            var obj = new
            {
                orderInfo = orderInfo,
                orderProgress= orderProgress,
                productionLife= productionLife
            };
            return Json(obj);
        }

        /// <summary>
        /// 获取一个工件的路由历史信息
        /// </summary>
        /// <param name="orderCode">订单编号</param>
        /// <param name="productionId">工件编号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetProductionUrlDetails(string orderCode,string productionId)
        {
            // 1、查找工件基本路由历史信息
            Pagination p = new Pagination();
            p.PageIndex = 1;
            p.PageSize = 1000;
            p.Sort = "UpdateTime";
            var productionInfo = await _orderService.SearchPassInformationByProductionCode(productionId, p);

            // 2、查找设备基本信息

            var obj = new
            {
                productionInfo = productionInfo
            };
            return Json(obj);
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="data">接收传递的订单列表</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateOrder([FromBody] object data)
        {
            var result = ChangeJsonObject(data);
            var orderList = result["orderList"];
            var _orderList = ChangeJsonObject(orderList);

            var serializer=new JavaScriptSerializer();
            var json = serializer.Serialize(_orderList);
            OrderDto t = serializer.Deserialize<OrderDto>(json);

            ResponseDto resultEntity = new ResponseDto();
            resultEntity.SerialID = Guid.NewGuid().ToString();
            resultEntity.Status = "fail";
            try
            {
                var orderEntity = _mapper.Map<OrderEntity>(t);
                await _orderService.SaveOrder(orderEntity);
                resultEntity.Status = "success";
            }
            catch(Exception ex)
            {
                resultEntity.Message = ex.Message;
            }                       
            return Json(resultEntity);
        }
        #endregion


        #region 辅助方法
        /// <summary>
        /// 将HTTP请求对象转换为便于操作的JSON对象
        /// </summary>
        /// <param name="data">req对象</param>
        /// <returns>JSON对象</returns>
        public IDictionary<string, object> ChangeJsonObject(object data)
        {
            var jsonobj = JsonConvert.SerializeObject(data);
            var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonobj);
            return result;
        }
        #endregion
    }
}
